<?php
namespace Wap\Controller;
use Think\Controller;
use Think\Log;
class WXPAY{
	const MODULE_SHOP = 1001;
}

class WxpayController extends Controller {
    private function getWxConfigHost(){
        $token = session('token');
        $host = '';
        //$host = 'www.ghygp.com';
        if($token){
            $wxConfig = M('wxuser')->where(array('token'=>$token))->find();
            $host = 'http://'.$wxConfig['host'].'/';
        }
        return $host;
    }
	//获取支付配置
	private function getConfig($token){

		$set = M('pay_config')->where(array('token'=>$token))->field('wxpay_config')->find();
		$set['config'] = unserialize($set['wxpay_config']);
		return array('APPID'=>$set['config']['appid'],'MCHID'=>$set['config']['mchid'],'KEY'=>$set['config']['key']);
	}

	/*乐富支付*/
	public function indexlefu()
	{
	    $tjurl = "http://www.lefusdk.com/pay.php";
	    $para['cpid'] = '1036';
	    $para['appid'] = '6036';
	    $para['user_id'] = $_SESSION['user_id'];
	    $para['cp_trade_no'] = $_GET['out_trade_no'];
	    $para['fee'] = $_GET['price'] * 100;  /*金额，以分为单位*/
	    $para['jump_url'] = $this->getWxConfigHost().'/wap/wxpay/jump/';   /*待定*/
	    $para['notify_url'] = $this->getWxConfigHost().'/wap/wxpay/notify/';

	    $para['w_type'] = 1;
        $isweixin = is_weixin();
        if( $isweixin == true )
        {
            $para['w_type'] = 1;
        }else{
            $para['w_type'] = 2;
        }

//        $string = "";
//        foreach( $para as $key=>$val )
//        {
//            $string = $key."=".$val."&";
//        }
//        $string = substr( $string, 0,strlen( $string ) - 1 );
//
//
//        $ch = curl_init( $tjurl."?".$string );
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
//        curl_setopt( $ch, CURLOPT_HEADER,1 );
//        $output = curl_exec( $ch );
//        curl_close( $ch );
//        echo $output;
//	    @header("Location:$stringurl");
//        exit();
//



        $def_url  = '<br /><form id="Form1" name="Form1" style="text-align:center;" method="get" action="'.$tjurl.'" target="_self">';
        foreach ($para as $key => $val) {
            $def_url = $def_url . '<input type="hidden" name="' . $key . '" value="' . $val . '" />';
//            $def_url = $def_url . '<input type="text" name="' . $key . '" value="' . $val . '" />';
        }

        $def_url .= '<input style="visibility:hidden" id="subbtn" type="submit" value="继续支付" />';
//        $def_url .= '<input style="display:block" id="subbtn" type="submit" value="继续支付" />';
        $def_url .= '</form>';
        $this->assign('callback',$def_url);
        $this->display();
	}

    /*98支付*/
	public function index(){
//	    $tjurl = "http://paytest.shopping98.com/scanpay/scan/pay/gateway";
	    $tjurl = "http://payment.shopping98.com/scan/pay/gateway";

//        $secret = "bcf18ce53f49407b9040a577b8c388fa";
        $secret = "3eced11b140c44a4be53561adf92acf8";

	    $array = array();
	    $array['service'] = "v1_scan_pay";
	    $array['version'] = "1.0";
	    $array['mch_no'] = "676988092351791104";
	    $array['charset'] = "UTF-8";
	    $array['req_time'] = date("YmdHis",time());
	    $array['sign_type'] = "MD5";
        $array['nonce_str'] = createNoncestr();

        $array['out_trade_no'] = $_GET['out_trade_no'];//test tmp
        $array['order_subject'] = "order";
        $array['acquirer_type'] = "wechat";
        $array['total_fee'] = $_GET['price'] * 100;//单位  分


        $array['return_url'] = $this->getWxConfigHost().'/wap/wxpay/returnurl';
//        $array['return_url'] = 'http://www.test.com';
        $array['notify_url'] = $this->getWxConfigHost().'/wap/wxpay/returnurl2';
//        $array['notify_url'] = 'http://www.test.com/wap/wxpay/synurl';
        $array['currency'] = "CNY";
        $array['client_ip'] = get_client_ip();
        $array['order_time'] = date("YmdHis",time());

        /*把发送给98的报文存储到sp_juejin_pay98*/
        M("juejin_pay98")->add( $array );

        $updatePlat['plat'] = "98";
        M('juejin_payorder')->where(['ordersn'=>$_GET['out_trade_no']])->save($updatePlat);

/*
------------------------------------------------------------
    edit by psycho@20170928
------------------------------------------------------------
*/
//        if($_GET['out_trade_no']){
//            $updateOrderPrize['price'] = $_GET['price'];
//            $order = M('juejin_payorder')->where(['ordersn'=>$_GET['out_trade_no']])->save($updateOrderPrize);
//        }
/*
------------------------------------------------------------
*/

        ksort( $array );

        $signstr = "";
        $i = 0;
        foreach( $array as $key=>$item )
        {
            if( $key == "sign_type" )
            {
                continue;
            }
            if( $item == "" || $item == null )
            {
                continue;
            }
            if( $i == 0 )
            {
                $signstr = $key."=".$item;
            }else{
                $signstr = $signstr."&".$key."=".$item;
            }
            $i++;
        }

        $signstr = $signstr.$secret;
        $array['sign'] = md5( $signstr );

         $ch = curl_init( $tjurl );
         curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
         curl_setopt( $ch, CURLOPT_HEADER,1 );

         curl_setopt( $ch, CURLOPT_POST,1 );
         curl_setopt( $ch, CURLOPT_POSTFIELDS, $array);
         $output = curl_exec( $ch );
         curl_close( $ch );

         if( $output )
         {
            $t1 = strstr(  $output, "code_url" );
            $url = substr($t1,11,strlen($t1)-11-2);

            $qrurl = qrcode( $url );
            $this->assign('imgurl',$qrurl );
            $this->assign("ifscan", "yes");
            $this->display();
         }
	}


	/*异步回调地址*/
	public function returnurl(){
        file_put_contents("apay.txt","returnurl",FILE_APPEND);
	    echo "这里是商户";
	}

	/*98支付的notify_url*/
	public function returnurl2(){
        $secret = "3eced11b140c44a4be53561adf92acf8";

        $ar1['charset']  = $_POST['charset'];
        $ar1['amount'] = $_POST['amount'];
        $ar1['trade_state'] = $_POST['trade_state'];
        $ar1['trade_time'] = $_POST['trade_time'];
        $ar1['bank_trade_no'] = $_POST['bank_trade_no'];
        $ar1['sign'] = $_POST['sign'];
        $ar1['mch_no'] = $_POST['mch_no'];
        $ar1['version'] = $_POST['version'];
        $ar1['resp_time'] = $_POST['resp_time'];
        $ar1['out_trade_no'] = $_POST['out_trade_no'];
        $ar1['resp_code'] = $_POST['resp_code'];
        $ar1['trade_no'] = $_POST['trade_no'];
        $ar1['currency'] = $_POST['currency'];
        $ar1['sign_type'] = $_POST['sign_type'];
        $ar1['acquirer_type'] = $_POST['acquirer_type'];

        /*签名*/
        ksort( $ar1 );
        $signstr = "";
        $i = 0;
        foreach( $ar1 as $key=>$item )
        {
            if( $key == "sign_type" || $key == "sign" )
            {
                continue;
            }
            if( $item == "" || $item == null )
            {
                continue;
            }
            if( $i == 0 )
            {
                $signstr = $key."=".$item;
            }else{
                $signstr = $signstr."&".$key."=".$item;
            }
            $i++;
        }

        $signstr = $signstr.$secret;
        $sign = md5( $signstr );

        $arret = array();
        $arret['ordersn'] = $ar1['out_trade_no'];
        $arret['amount'] = $ar1['amount'];
        $xml = file_get_contents("php://input");
        $arret['str'] = $xml;
        M("juejin_payret")->add( $arret );


        if( $sign == $ar1['sign'] ){

            file_put_contents("充值.txt",$xml,FILE_APPEND);
            file_put_contents("充值.txt","\r\n",FILE_APPEND);

            if( $ar1['resp_code'] == '0000' )
            {
                $this->addmoney( $ar1['out_trade_no'], $ar1['amount'], "98" );
                echo "success";
            }
        }else{
        }
	}

	private function addmoney( $ordersn, $money, $plat ){
        $order = M('juejin_payorder')->where(array('ordersn'=>$ordersn ))->select();
        if( count( $order ) == 1 )
        {
            if($order[0]['status'] != 2){
                /*
                $price = 0.97 * floatval( $price );
                $price = sprintf("%.2f", $price);
                */

//                $monval = 0.97 * floatval( $order[0]['price'] );
//                $monval = sprintf("%.2f", $monval);
//                $monval2 = 0.03 * floatval( $order[0]['price'] );
//                $monval2 = sprintf("%.2f", $monval2);
                if( $money/100 != $order[0]['price'] )
                {
                    $str = var_export( $order,TRUE );
                    file_put_contents("error.txt",$str,FILE_APPEND);
                    file_put_contents("error.txt","\r\n",FILE_APPEND);
                    file_put_contents("error.txt",$money,FILE_APPEND);
                    file_put_contents("error.txt","\r\n",FILE_APPEND);
                }

                $money = $money/100;


                $monval = 0.97 * floatval( $money );
                $monval = sprintf("%.2f", $monval);
                $monval2 = 0.03 * floatval( $money );
                $monval2 = sprintf("%.2f", $monval2);





                M('juejin_payorder')->where(array('ordersn'=>$ordersn))->save(['status'=>2,'paytime'=>time(),'plat'=>$plat]);
                M('juejin_users')->where(['id'=>$order[0]['userid']])->setInc('money',$monval );
                M('juejin_users')->where(['id'=>$order[0]['userid']])->setInc('addmoney',$monval );

                /*积分日志*/
                $log['userid'] = $order[0]['userid'];
                $log['num'] = $monval;
                $log['type'] = 1;
                $log['createtime'] = time();
                $log['note'] = 1;
                M("juejin_integral_log")->add( $log );


                $log['userid'] = 0;
                $log['num'] = $monval2;
                $log['type'] = 1;
                $log['createtime'] = time();
                $log['note'] = 2;
                M("juejin_integral_log")->add( $log );

                return "success";;
            }else{
                return "success";
            }
        }else{
            return "trnorepeat";
        }
	}




    /*异步回调地址*/
	public function synurl(){
        $ch = curl_init( "http://www.flksj2013.cn/allpay/payorder" );
         curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
         curl_setopt( $ch, CURLOPT_HEADER,1 );

         $post_data = array("merId"=>$merid,"attach"=>time(),"merNo"=> $_GET['out_trade_no'], "title"=>'tradeplatformcharge', "describe"=> "tradeplatformcharge",
                "payType"=>$paytype,"price"=>$_GET['price'], "notifyUrl"=>$this->getWxConfigHost().'/wap/wxpay/notify/', "synUrl"=>$this->getWxConfigHost().'/wap/wxpay/synurl/',"sign"=>$sign);

         curl_setopt( $ch, CURLOPT_POST,1 );
         curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_data);
         $output = curl_exec( $ch );
         curl_close( $ch );

         $str1 = strstr( $output, "GMT" );
         $str2 = substr( $str1, 4, strlen( $str1 ) );

         echo is_null( json_decode( $str2 ) );
         $test = json_decode( $str2 );
         $orderUrl = urldecode( $test->data->orderUrl );
//         echo $orderUrl;
         @header("Location:$orderUrl");
	}




    /*全民金服*/
    public function indexquanminjinfu(){
        $appkey = "6413f866b558d3e2b6ccf4f0d865f9df";
        $keyvalue = "u4smNesRMrDAIU62HXNy1eoeP9uD8yaUKCcd103j";
        $tjurl = "https://testpayapi.aijinfu.cn/pay/multifunctionPayment.do";

        $parray = array();
        $parray['appKey'] = $appkey;
        $parray['bussOrderNum'] = $_GET['out_trade_no'];
        $parray['orderName'] = "MicroTransaction";
        $parray['notifyUrl'] = $this->getWxConfigHost().'/wap/wxpay/notifyqmjf/';
        $parray['returnUrl'] = $this->getWxConfigHost();
        $parray['ip'] = getClientIP();
        $parray['payMoney'] = $_GET['price'];

        $tmp = get_device_type();

        if( $tmp == "android" )
        {
            $parray['appType'] = 1;
        }else if( $tmp == "ios" )
        {
            $parray['appType'] = 2;
        }
        /*微信公众号*/
//        $isweixin = is_weixin();
//        if( $isweixin == true )
//        {
//            $parray['payPlatform'] = 2;
//        }
        $parray['payPlatform'] = 2;


        ksort( $parray );
        $stringA = "";
        foreach( $parray as $key=>$value )
        {
            if( $value != null || $value != "" )
            $stringA = $stringA."&".$key."=".urlencode($value);
        }
        $stringA = $keyvalue.$stringA;
        $sign = md5(strtoupper($stringA));
        $parray['sign'] = $sign;


        $stringB = "";
        foreach( $parray as $key=>$value )
        {
            if( $value != null || $value != "" )
            $stringB = $stringB."&".$key."=".urlencode($value);
        }

        $stringB = substr( $stringB, 1, strlen( $stringB ) );


        $def_url  = '<br /><form id="Form1" style="text-align:center;" method="get" action="'.$tjurl.'" target="_blank">';
//        foreach ($para as $key => $val) {
//            $def_url = $def_url . '<input type="text" name="' . $key . '" value="' . $val . '" />';
//        }
//
        $def_url = $def_url . '<input type="text" name="paramStr" value="' . $stringB . '" />';

        $def_url .= '<input style="display:none" type="submit" value="继续支付" />';
        $def_url .= '</form>';
        $this->assign('callback',$def_url);
        $this->display();
    }
    /*
    通付宝
    */
	public function index2()
    {
         /*curl*/
         $paytype = "WW";
         $merid = "0010201708110170";
         $secretkey = "589d3acaa63049ec9689da25b0722e69";
         $para['merId'] = $merid;
         $para['attach'] = time();
         $para['merNo'] = $_GET['out_trade_no'];
         $para['title'] = 'tradeplatformcharge';
         $para['describe'] = 'tradeplatformcharge';
         $para['payType'] = $paytype;   /*待定*/
         $para['price'] = $_GET['price'];
         $para['notifyUrl'] = $this->getWxConfigHost().'/wap/wxpay/notify/';
         $para['synUrl'] = $this->getWxConfigHost().'/wap/wxpay/synurl/';
         ksort( $para );
         $stringA = "";
         foreach( $para as $key=>$value )
         {
             if( $value != null || $value != "" )
             $stringA = $stringA.$key."=".urlencode($value)."&";
         }


//           $signTmp = $stringA."&&589d3acaa63049ec9689da25b0722e69";
           $signTmp = substr( $stringA, 0, strlen($stringA)-1 );

//           echo "<br/>".$signTmp."<br/>";

           $signTmp = $signTmp."&&&".$secretkey;

//            echo "<br/>".$signTmp."<br/>";
         $sign = md5( $signTmp );


         $ch = curl_init( "http://www.flksj2013.cn/allpay/payorder" );
         curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
         curl_setopt( $ch, CURLOPT_HEADER,1 );

         $post_data = array("merId"=>$merid,"attach"=>time(),"merNo"=> $_GET['out_trade_no'], "title"=>'tradeplatformcharge', "describe"=> "tradeplatformcharge",
                "payType"=>$paytype,"price"=>$_GET['price'], "notifyUrl"=>$this->getWxConfigHost().'/wap/wxpay/notify/', "synUrl"=>$this->getWxConfigHost().'/wap/wxpay/synurl/',"sign"=>$sign);

         curl_setopt( $ch, CURLOPT_POST,1 );
         curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_data);
         $output = curl_exec( $ch );
         curl_close( $ch );

         $str1 = strstr( $output, "GMT" );
         $str2 = substr( $str1, 4, strlen( $str1 ) );

         echo is_null( json_decode( $str2 ) );
         $test = json_decode( $str2 );
         $orderUrl = urldecode( $test->data->orderUrl );
//         echo $orderUrl;
         @header("Location:$orderUrl");
    }



	//支付发启页面 （原版的，已经废弃）
	public function indexold(){

		$tjurl = "http://zf.cnzypay.com/Pay_Index.html";   //提交地址
		//$module="CNZYZF";
		$this->token = I('get.token','','trim');
		empty($this->token) && exit("<h2>参数错误：token不能为空！</h2>");
		$this->wechat_id = I('get.wechat_id','','trim');
		//支付场景模块
		$module = I('get.module',WXPAY::MODULE_SHOP,'intval');
		$out_trade_no = I('get.out_trade_no','','trim');
		//获取订单详细信息
		$order = $this->getOrderDetail($this->token,$out_trade_no,$module);
		$this->wechat_id = I('get.wechat_id','','trim');
		Log::write("__wechat_id".$this->wechat_id,'wchart_INFO');
		//$Md5key="RVEDFulA9lzKjppaQfC5nqQpVtM8PD";    //商户密钥
		$Md5key="yOQr8xiuyGF1Vpxz2poqRsqTeYp8pY";    //商户密钥
		$pay_memberid = "11834";    //商户ID
		//$pay_memberid = $pay_memberid;
		$pay_orderid = $out_trade_no;    //订单号 $data['ordersn']
		$pay_amount = $order['total_fee'];

		$pay_applydate = date("Y-m-d H:i:s");
		$pay_bankcode = "WXZF";   //银行编码
		//$pay_notifyurl = $this->getWxConfigHost().'/wap/wxpay/notify/';//."&code=".$payment['code'];
		//$pay_notifyurl = 'http://ceshi.snxweb.com/wap/wxpay/notify';//."&code=".$payment['code'];


		$pay_notifyurl='http://10.kuhusoft.cn/wap/wxpay/notify/token/'.$this->token.'.html';

		//$pay_callbackurl =I('get.callback',$this->getWxConfigHost().U('Wxpay/paySuccess'),'urldecode');


		$pay_callbackurl ='http://10.kuhusoft.cn'.U('Wxpay/paySuccess');


		$requestarray = array(
				"pay_memberid" => $pay_memberid,
				"pay_orderid" => $pay_orderid,
				"pay_amount" => $pay_amount,
				"pay_applydate" => $pay_applydate,
				"pay_bankcode" => $pay_bankcode,
				"pay_notifyurl" => $pay_notifyurl,
				"pay_callbackurl" => $pay_callbackurl
		);


		ksort($requestarray);
		reset($requestarray);
		$md5str = "";
		foreach ($requestarray as $key => $val) {
			$md5str = $md5str . $key . "=>" . $val . "&";
		}
		//echo($md5str . "key=" . $Md5key."<br>");
		$sign = strtoupper(md5($md5str . "key=" . $Md5key));
		$requestarray["pay_md5sign"] = $sign;

		$requestarray["tongdao"] = "WftWx";   //公众号支付通道

		//当前操作者的微信id 唯一标示符号
		$requestarray["pay_reserved1"] = $this->wechat_id;

		$requestarray["pay_reserved3"] = $this->wechat_id;


		//$def_url  = '<br /><form style="text-align:center;" method="post" action="'.$this->gateway.' "target="_blank">';

		$def_url  = '<br /><form id="Form1" style="text-align:center;" method="post" action="'.$tjurl.'" target="_blank">';


		foreach ($requestarray as $key => $val) {
			$def_url = $def_url . '<input type="hidden" name="' . $key . '" value="' . $val . '" />';
		}
		$def_url .= '<input type="submit" value="继续支付,充值不到账联系客服微信：weijiaoyizhuli" />';
		$def_url .= '</form>';
		//$def_url .= ' document.Form1.submit()';

		//$this->assign("PayPackage",$requestarray);
		$this->assign('callback',$def_url);
		$this->assign('order',$order);
		$this->display('index');

	}

	public function test(){
	    $string = "HTTP/1.1 302 Found Date: Fri, 18 Aug 2017 02:49:20 GMT Server: Apache X-Powered-By: PHP/5.3.3 Location: http://www.lefusdk.com/desktop/wpay-wap_app.php?request_redis_id=170818104920364B0L3RR8V Content-Length: 0 Connection: close Content-Type: text/html; charset=UTF-8";
	    $string1 =  strstr( $string, "http://" );
	    $string2 =  strpos( $string1, " Content-Length:" );
	    echo substr( $string1, 0, $string2 );
	}

	/*lefu*/
	public function notify(){
        $xml = file_get_contents("php://input");
        file_put_contents("notifypsot.txt","\r\n",FILE_APPEND);
        file_put_contents("notifypsot.txt",$xml,FILE_APPEND);

        $inputdata = json_decode( $xml );

        $secretkey = "10366036frc6";
	    $data['appid'] = $inputdata->appid;
	    $data['cp_trade_no'] = $inputdata->cp_trade_no;
	    $data['cpid'] = $inputdata->cpid;
	    $data['fee'] = $inputdata->fee;
	    $data['pay_transaction_id'] = $inputdata->pay_transaction_id;
	    $data['result_code'] = $inputdata->result_code;
	    $data['user_id'] = $inputdata->user_id;
        ksort( $data );
        $stringA = "";
        foreach( $data as $key=>$value )
        {
            if( $value != null || $value != "" )
            $stringA = $stringA.$key."=".urlencode($value)."&";
        }
        $stringA = $stringA."key=".$secretkey;
        $stringA = $stringA.strtoupper();
        $sign =md5($stringA);

        file_put_contents("notifypsot.txt",$inputdata->sign,FILE_APPEND);
        file_put_contents("notifypsot.txt",$data['cp_trade_no'],FILE_APPEND);

        if( strtoupper($sign) == $inputdata->sign  )
        {
            $order = M('juejin_payorder')->where(array('ordersn'=>$data['cp_trade_no']))->select();
            if( count( $order ) == 1 )
            {
                if($order['status'] != 2){
                    M('juejin_payorder')->where(array('ordersn'=>$data['cp_trade_no']))->save(['status'=>2,'paytime'=>time()]);
                    M('juejin_users')->where(['id'=>$data['user_id']])->setInc('money',$data['fee']/100);
                    M('juejin_users')->where(['id'=>$data['user_id']])->setInc('addmoney',$data['fee']/100);

                    echo "success";
                }else{
                    echo "already pay";
                }
            }else{
                echo "trnorepeat";
            }
        }else{
            echo "sign error";
        }
	}


	public function notifyqmjf()
	{
        $xml = file_get_contents("php://input");
        file_put_contents("notifyqmjfpsot.txt","\r\n",FILE_APPEND);
        file_put_contents("notifyqmjfpsot.txt","input".$xml,FILE_APPEND);
        file_put_contents("notifyqmjfpsot.txt","\r\n",FILE_APPEND);
        file_put_contents( "notifyqmjfpsot.txt", "post", I("post.") );
        file_put_contents("notifyqmjfpsot.txt","\r\n",FILE_APPEND);
        file_put_contents( "notifyqmjfpsot.txt", "get", I("get.") );
	}


	/*lefu*/
	public function jump(){
	    $url = $_SERVER['SERVER_NAME'];
        $url = "http://".$url;
        @header("Location:$url");
        exit();
	}


	public function notifyOld(){
		/*
		$this->token = I('get.token','','trim')
		$xml = file_get_contents("php://input");
		Log::write("[WXPAY]:xml=".$xml,'DEBUG');

		Vendor("WxPayV3.WxPayPubHelper");
		//使用通用通知接口
		$notify = new \Notify_pub();
		$config = $this->getConfig($this->token);
		$notify->KEY = $config['KEY'];
		//存储微信的回调
		$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
		$notify->saveData($xml);



		$ReturnArray = array( // 返回字段
				"memberid" => $_REQUEST["memberid"], // 商户ID
				"orderid" =>  $_REQUEST["orderid"], // 订单号
				"amount" =>  $_REQUEST["amount"], // 交易金额
				"datetime" =>  $_REQUEST["datetime"], // 交易时间
				"returncode" => $_REQUEST["returncode"]
		);

		$Md5key = "yOQr8xiuyGF1Vpxz2poqRsqTeYp8pY";    //就是这里,验证回调的商户密钥
		//$sign = $this->md5sign($Md5key, $ReturnArray);

		///////////////////////////////////////////////////////
		ksort($ReturnArray);
		reset($ReturnArray);
		$md5str = "";
		foreach ($ReturnArray as $key => $val) {
			$md5str = $md5str . $key . "=>" . $val . "&";
		}
		$sign = strtoupper(md5($md5str . "key=" . $Md5key));
		///////////////////////////////////////////////////////
		if ($sign == $_REQUEST["sign"]) {
			if ($_REQUEST["returncode"] == "00") {
				$str = "交易成功！订单号：".$_REQUEST["orderid"];
				//设置订单号 和  wechat_id
				$notify->data['out_trade_no']=$_REQUEST["orderid"];
				//$this->wechat_id = I('get.wechat_id','','trim');
				//修改openid  也就是 wecahrtid
				$notify->data['openid']=$_REQUEST["reserved1"];
				//更新订单状态
				$this->ZyZfupdateOrderState($notify->data);
				echo OK;
			}
		}*/
	}



	/**@desc 更新订单状态
	 * @param array data: out_trade_no,openid
	 */
	protected function ZyZfupdateOrderState($data){

		//支付业务
//		 $order = M('juejin_payorder')->where(array('ordersn'=>$data['out_trade_no'],'wechat_id'=>$data['openid']))->find();
		 $order = M('juejin_payorder')->where(array('ordersn'=>$data['out_trade_no']))->find();
		if($order['status'] != 2){
			M('juejin_payorder')->where(array('ordersn'=>$data['out_trade_no'],'wechat_id'=>$data['openid']))->save(['status'=>2,'paytime'=>time()]);
			M('juejin_users')->where(['id'=>$order['userid']])->setInc('money',$order['price']);

			M('juejin_users')->where(['id'=>$order['userid']])->setInc('addmoney',$order['price']);
		}


	/*	//if($order['price']>=100){

			//M('juejin_users')->where(['id'=>$order['userid']])->setInc('money',$order['price']);   //这行是累加反利金额的,条件是大于100 注释掉就不返利
		//}

		 */


/*

		$order = M('juejin_payorder')->where(array('ordersn'=>$data['out_trade_no']))->find();
		M('juejin_payorder')->where(array('ordersn'=>$data['out_trade_no']))->save(['status'=>2,'paytime'=>time()]);
		M('juejin_users')->where(['id'=>$order['userid']])->setInc('money',$order['price']);

		M('juejin_users')->where(['id'=>$order['userid']])->setInc('addmoney',$order['price']);

		if($order['price']>=0){
			M('juejin_users')->where(['id'=>$order['userid']])->setInc('money',$order['price']);
		}


		 */



		/*$user = M('juejin_users')->where(['id'=>$order['userid']])->find();*/


		/* if($user['shareid']){//上级返利
		 $fanli = $order['price']*0.1;
		 M('juejin_users')->where(['id'=>$user['shareid']])->setInc('money',$fanli);
		 //添加返利记录表
		 M('juejin_fanliorder')->add(['userid'=>$order['userid'],'wechat_id'=>$data['openid'],'touserid'=>$user['shareid'],
		 'price'=>$fanli,'status'=>2,'createtime'=>time()]);

		 } */

	}

	/**
	 *@method getOrderDetail
	 *@desc 通过订单号获取支付详情
	 *@param string token
	 *@param string orderId
	 *@param int module
	 */
	protected function getOrderDetail($token,$orderId,$module){
		$ret = array();
		switch($module){
			case WXPAY::MODULE_SHOP:
				$order = M('juejin_payorder')->where(array('ordersn'=>$orderId))->find();
				$ret['total_fee'] = $order['price'];//0.1;
				if($_SESSION['user_id']==27){$ret['total_fee'] = 0.1;}//0.1;}
				$ret['body'] = '会员充值';
				return $ret;
			case "CNZYZF":

				$order = M('juejin_payorder')->where(array('ordersn'=>$orderId))->find();
				$ret['total_fee'] = 0.01;//0.1;

				//$ret['total_fee'] = $order['price'];//0.1;

				if($_SESSION['user_id']==27){$ret['total_fee'] = 0.1;}//0.1;}
				$ret['body'] = '会员充值';
				return $ret;

		}
		return null;
	}

	/**@desc 更新订单状态
	 * @param array data: out_trade_no,openid
	 */
	protected function updateOrderState($data,$token){
		$module = intval($data['attach']);
		if($module == WXPAY::MODULE_SHOP){
			//支付业务
			$order = M('juejin_payorder')->where(array('ordersn'=>$data['out_trade_no'],'wechat_id'=>$data['openid']))->find();
			M('juejin_payorder')->where(array('ordersn'=>$data['out_trade_no'],'wechat_id'=>$data['openid']))->save(['status'=>2,'paytime'=>time()]);
			M('juejin_users')->where(['id'=>$order['userid']])->setInc('money',$order['price']);

			M('juejin_users')->where(['id'=>$order['userid']])->setInc('addmoney',$order['price']);


		}

	}

	//保存通知记录,如果已经存在则返回false
	public function checkNotify($token,$notify){
		$data['transaction_id'] = $notify['transaction_id'];
		$data['out_trade_no'] = $notify['out_trade_no'];
		$data['openid'] = $notify['openid'];
		$data['time_end'] = $notify['time_end'];
		$data['total_fee'] = floatval($notify['total_fee'])/100;
		$data['bank_type'] = $notify['bank_type'];
		$data['module'] = $notify['attach'];
		$data['trade_type'] = $notify['trade_type'];
		$data['is_subscribe'] = $notify['is_subscribe'];
		$data['token'] = $token;
		$check = M('wxpay_notify')->where(['transaction_id'=>$notify['transaction_id']])->count();
		if($check==0){
			M('wxpay_notify')->add($data);
		}
		return true;
	}
	//原生支付通知接口
	public function native(){

	}

	//支付成功跳转页面
	public function paySuccess(){
		$this->assign('order_id',$_GET['oid']);
		$this->display('paysuccess');
	}

	//支付失败跳转页面
	public function payError(){

	}

	//用户维权接口
	public function rights(){
		$xml = get_http_body();
		$content = xml2array($xml);
		$data['openid'] = $content['OpenId'];
		$data['msg_type'] = $content['MsgType'];
		$data['feed_back_id'] = $content['FeedBackId'];
		$data['trans_id'] = $content['TransId'];
		$data['reason'] = $content['Reason'];
		$data['solution'] = $content['Solution'];
		$data['extinfo'] = $content['ExtInfo'];
		$data['time'] = $content['TimeStamp'];

		M('customer_rights')->add($data);
	}

	//系统告警
	public function alarm(){
		$xml = get_http_body();
		$alarm = xml2array($xml);
		$data['error_type'] = $alarm['ErrorType'];
		$data['desc'] = $alarm['Description'];
		$data['content'] = $alarm['AlarmContent'];
		$data['time'] = $alarm['TimeStamp'];

		M('alarm')->add($data);
		echo 'success';
	}

	//微信发货通知
	public function fahuo(){
		$oid = I('get.oid','','trim');
		$pay = new \Wap\Logic\Wxpay($this->token);
		$this->ajaxReturn($pay->delivernotify($oid));
	}

    /*微信公众号支付*/
    public function wechatpay(){
        $secret = "XBOmyREMfWnlSfNMwHkmT7No6cZzBvPd";
        $tjurl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $parameters["appid"] = "wxe7d2cf27b4cd9b87";
        $parameters["mch_id"] = "1470987702";
        $parameters["nonce_str"] = createNoncestr();
        $parameters["sign"] = "";
        $parameters["body"] = "水果店-苹果";
        $parameters["out_trade_no"] = $_GET['out_trade_no'];
        $parameters["total_fee"] = $_GET['price'] * 100;
        $parameters["spbill_create_ip"] = get_client_ip();
        $parameters["notify_url"] = $this->getWxConfigHost().'/wap/wxpay/wechanotifyurl';
        $parameters["trade_type"] = "JSAPI";
        $parameters["openid"] = $this->GetPayOpenid();

        $updatePlat['plat'] = "wechat";
        M('juejin_payorder')->where(['ordersn'=>$_GET['out_trade_no']])->save($updatePlat);
        /*签名*/
        ksort( $parameters );
        $signstr = "";
        $i = 0;
        foreach( $parameters as $key=>$item )
        {
            if( $key == "sign_type" )
            {
                continue;
            }
            if( $item == "" || $item == null )
            {
                continue;
            }
            if( $i == 0 )
            {
                $signstr = $key."=".$item;
            }else{
                $signstr = $signstr."&".$key."=".$item;
            }
            $i++;
        }

        $signstr = $signstr."&key=".$secret;
        $parameters['sign'] = strtoupper( md5( $signstr ) );

        /*把发送给微信支付的内容存储到表中*/
        M("juejin_paywechat")->add( $parameters );

        $xml = $this->arrayToXml($parameters);
        $this->postXmlCurl($xml,$tjurl,30,$parameters["total_fee"],$secret);
    }

    public function test1(){
        echo "fdsakfposdjnfiuu";
    }

    /*易迅通宝公众号支付*/
    public function wechatpayyx(){
        $secret = "3WbazjHRqoWTcfwoUgWC1P85osMR8wUQ";
        $tjurl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $parameters["appid"] = "wx7ba4eebab3b4f968";
        $parameters["mch_id"] = "1480975722";
        $parameters["nonce_str"] = createNoncestr();
        $parameters["sign"] = "";
        $parameters["body"] = "易迅通宝";
        $parameters["out_trade_no"] = 'K'.substr(time(),4,10).rand(10,99);;
//        $parameters["out_trade_no"] = $_GET['out_trade_no'];
//        $parameters["total_fee"] = $_GET['price'] * 100;
        $parameters["total_fee"] = 0.01;
        $parameters["spbill_create_ip"] = get_client_ip();
        $parameters["notify_url"] = $this->getWxConfigHost().'/wap/wxpay/wechanotifyurlyx';
        $parameters["trade_type"] = "JSAPI";
        $parameters["openid"] = $this->GetPayOpenid();

        $updatePlat['plat'] = "wechatyixun";
        M('juejin_payorder')->where(['ordersn'=>$parameters["out_trade_no"]])->save($updatePlat);
        /*签名*/
        ksort( $parameters );
        $signstr = "";
        $i = 0;
        foreach( $parameters as $key=>$item )
        {
            if( $key == "sign_type" )
            {
                continue;
            }
            if( $item == "" || $item == null )
            {
                continue;
            }
            if( $i == 0 )
            {
                $signstr = $key."=".$item;
            }else{
                $signstr = $signstr."&".$key."=".$item;
            }
            $i++;
        }

        $signstr = $signstr."&key=".$secret;
        $parameters['sign'] = strtoupper( md5( $signstr ) );

        /*把发送给微信支付的内容存储到表中*/
        M("juejin_paywechat")->add( $parameters );

        $xml = $this->arrayToXml($parameters);
        $this->postXmlCurl($xml,$tjurl,30,$parameters["total_fee"],$secret);
    }



    /*微信公众号查询订单*/
    public function queryWechatOrder(){

        $secret = "XBOmyREMfWnlSfNMwHkmT7No6cZzBvPd";
        $tjurl = "https://api.mch.weixin.qq.com/pay/orderquery";
//        $sql = "select * from sp_juejin_payorder where plat = 'wechat' and  status = 0 and createtime > '".(time()-15*60)."'";
//        $sql = "select * from sp_juejin_payorder where plat = 'wechat' and  status = 0 and createtime > 1506787200";
        /*轮询前一个小时到前2分钟的订单*/
        $sql = "select * from sp_juejin_payorder where plat = 'wechat' and  status = 0 and createtime between ".(time()-3600)." and ".(time()-2*60);
        $d1 = M("juejin_payorder")->query($sql);

        for( $i = 0;$i <count($d1); $i++ ) {
            $parameters = array();
            $parameters['appid'] = "wxe7d2cf27b4cd9b87";
            $parameters['mch_id'] = "1470987702";
            $parameters['out_trade_no'] = $d1[$i]['ordersn'];
            $parameters['nonce_str'] = createNoncestr();
            $parameters['sign'] = "";
            /*签名*/
            ksort( $parameters );
            $signstr = "";
            $index = 0;
            foreach( $parameters as $key=>$item )
            {
                if( $key == "sign_type" )
                {
                    continue;
                }
                if( $item == "" || $item == null )
                {
                    continue;
                }
                if( $index == 0 )
                {
                    $signstr = $key."=".$item;
                }else{
                    $signstr = $signstr."&".$key."=".$item;
                }
                $index++;
            }

            $signstr = $signstr."&key=".$secret;
            $parameters['sign'] = strtoupper( md5( $signstr ) );

            $xml = $this->arrayToXml($parameters);
            //初始化curl
            $ch = curl_init();
            //设置超时
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            //这里设置代理，如果有的话
            //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
            //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
            curl_setopt($ch,CURLOPT_URL, $tjurl);
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
            //设置header
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            //要求结果为字符串且输出到屏幕上
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            //post提交方式
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
            //运行curl
            $data = curl_exec($ch);
            curl_close($ch);
            //返回结果


            if($data){
                $resu = $this->xmlToArray($data);
                print_r( $resu );
                echo "<br/>";
                if( $resu['return_code'] == "SUCCESS" ){
                    if( $resu['result_code'] == "SUCCESS" ){
                        if( $resu['trade_state'] == "SUCCESS" ){
                            $this->wechatGetReturn( $resu,$secret );
                        }else{
                            M("juejin_payorder")->where(['ordersn'=>$d1[$i]['ordersn']])->save(['status'=>3]);
                            $aryret = array();
                            $aryret['ordersn'] = $d1[$i]['ordersn'];
                            $aryret['str'] = $d1[$i]['trade_state'];
                            /*0:微信异步回掉  1：微信查询订单  2：98异步回掉*/
                            $aryret['sour'] = 1;
                            $aryret['savetime'] = time();
                            M("juejin_payret")->add( $aryret );
                        }
                    }else if ($resu['result_code'] == "FAIL"){
                        /*支付失败*/
                        M("juejin_payorder")->where(['ordersn'=>$d1[$i]['ordersn']])->save(['status'=>3]);
                        $aryret = array();
                        $aryret['ordersn'] = $d1[$i]['ordersn'];
                        $aryret['str'] = $d1[$i]['err_code']."||".$d1[$i]['err_code_des'];
                        /*0:微信异步回掉  1：微信查询订单  2：98异步回掉*/
                        $aryret['sour'] = 1;
                        $aryret['savetime'] = time();
                        M("juejin_payret")->add( $aryret );
                    }
                }
            }
        }//for循环结束
    }


    public function queryWechatOrdersingle(){
            $ordersn = $_GET['ordersn'];
            $secret = "XBOmyREMfWnlSfNMwHkmT7No6cZzBvPd";
            $tjurl = "https://api.mch.weixin.qq.com/pay/orderquery";
    //        $sql = "select * from sp_juejin_payorder where plat = 'wechat' and  status = 0 and createtime > '".(time()-15*60)."'";
            $sql = "select * from sp_juejin_payorder where ordersn = '".$ordersn."'";
            $d1 = M("juejin_payorder")->query($sql);

            for( $i = 0;$i <count($d1); $i++ ) {
                $parameters = array();
                $parameters['appid'] = "wxe7d2cf27b4cd9b87";
                $parameters['mch_id'] = "1470987702";
                $parameters['out_trade_no'] = $d1[$i]['ordersn'];
                $parameters['nonce_str'] = createNoncestr();
                $parameters['sign'] = "";
                /*签名*/
                ksort( $parameters );
                $signstr = "";
                $index = 0;
                foreach( $parameters as $key=>$item )
                {
                    if( $key == "sign_type" )
                    {
                        continue;
                    }
                    if( $item == "" || $item == null )
                    {
                        continue;
                    }
                    if( $index == 0 )
                    {
                        $signstr = $key."=".$item;
                    }else{
                        $signstr = $signstr."&".$key."=".$item;
                    }
                    $index++;
                }

                $signstr = $signstr."&key=".$secret;
                $parameters['sign'] = strtoupper( md5( $signstr ) );

                $xml = $this->arrayToXml($parameters);
                //初始化curl
                $ch = curl_init();
                //设置超时
                curl_setopt($ch, CURLOPT_TIMEOUT, 30);
                //这里设置代理，如果有的话
                //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
                //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
                curl_setopt($ch,CURLOPT_URL, $tjurl);
                curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
                curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
                //设置header
                curl_setopt($ch, CURLOPT_HEADER, FALSE);
                //要求结果为字符串且输出到屏幕上
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
                //post提交方式
                curl_setopt($ch, CURLOPT_POST, TRUE);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
                //运行curl
                $data = curl_exec($ch);
                curl_close($ch);
                //返回结果


                print_r( $data );

                if($data){
                    $resu = $this->xmlToArray($data);
                    print_r( $resu );
                    echo "<br/>";
                    if( $resu['return_code'] == "SUCCESS" ){
                        if( $resu['result_code'] == "SUCCESS" ){
                            if( $resu['trade_state'] == "SUCCESS" ){
                                $this->wechatGetReturn( $resu,$secret );
                            }else{
                                M("juejin_payorder")->where(['ordersn'=>$d1[$i]['ordersn']])->save(['status'=>3]);
                                $aryret = array();
                                $aryret['ordersn'] = $d1[$i]['ordersn'];
                                $aryret['str'] = $d1[$i]['trade_state'];
                                M("juejin_payret")->add( $aryret );
                            }
                        }else if ($resu['result_code'] == "FAIL"){
                            /*支付失败*/
                            M("juejin_payorder")->where(['ordersn'=>$d1[$i]['ordersn']])->save(['status'=>3]);
                            $aryret = array();
                            $aryret['ordersn'] = $d1[$i]['ordersn'];
                            $aryret['str'] = $d1[$i]['err_code']."||".$d1[$i]['err_code_des'];
                            M("juejin_payret")->add( $aryret );
                        }
                    }
                }
            }//for循环结束
        }




    public function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
                $xml.="<".$key.">".$val."</".$key.">";
        }
        $xml.="</xml>";
        return $xml;
    }

    /*微信支付通知地址*/
    public function wechanotifyurl(){
        $secret = "XBOmyREMfWnlSfNMwHkmT7No6cZzBvPd";
        $xml = file_get_contents("php://input");
        $this->getXMLInfo();
        /*验证签名*/
        $parameters = $this->xmlArr;
        $this->wechatGetReturn( $parameters,$secret, "wechat" );
    }

    /*易讯通宝微信支付通知地址*/
    public function wechanotifyurlyx(){
        $secret = "3WbazjHRqoWTcfwoUgWC1P85osMR8wUQ";
        $xml = file_get_contents("php://input");
        $this->getXMLInfo();
        /*验证签名*/
        $parameters = $this->xmlArr;
        $this->wechatGetReturn( $parameters,$secret, "wechatyx" );
    }

    /*支付成功 微信公众号针对查询或者异步通知接口 获得的xml信息，校验签名，获得增加的金额*/
    public function wechatGetReturn($parameters,$secret,$plat){
        ksort( $parameters );
        $signstr = "";
        $i = 0;
        foreach( $parameters as $key=>$item )
        {
            if( $key == "sign" )
            {
                continue;
            }
            if( $item == "" || $item == null )
            {
                continue;
            }
            if( $i == 0 )
            {
                $signstr = $key."=".$item;
            }else{
                $signstr = $signstr."&".$key."=".$item;
            }
            $i++;
        }

        $signstr = $signstr."&key=".$secret;

        $sign = strtoupper( md5( $signstr ) );

        $aryret = array();
        $aryret['ordersn'] = $parameters['out_trade_no'];
        $aryret['amount'] = $parameters['total_fee'];
        $aryret['str'] = var_export($parameters,TRUE);
        $aryret['sour'] = 0;
        $aryret['savetime'] = time();
        M("juejin_payret")->add( $aryret );

        if( $sign== $parameters['sign']  )
        {
            /*签名验证通过*/
            $xml = var_export($parameters,true);
            file_put_contents("wcz.txt",$xml,FILE_APPEND);
            file_put_contents("wcz.txt","\r\n",FILE_APPEND);
            if( $parameters['result_code'] == "SUCCESS" && $parameters['return_code'] == "SUCCESS" && $parameters['trade_state'] == "SUCCESS"){
                $this->addmoney( $parameters['out_trade_no'],  $parameters['total_fee'], $plat );
                echo "success";
            }
        }
    }


     public function getXMLInfo(){
        ob_clean();
        $xmlStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if(!empty($xmlStr)){
            $this->xmlArr = json_decode(json_encode(simplexml_load_string($xmlStr, 'SimpleXMLElement', LIBXML_NOCDATA)),TRUE);
            $this->xmlArr['Time'] = time();
        }else{
            return false;
        }
    }




        /**
         * 	作用：以post方式提交xml到对应的接口url
         */
        public function postXmlCurl($xml,$url,$second=30,$fee,$secret)
        {
            //初始化curl
            $ch = curl_init();
            //设置超时
            curl_setopt($ch, CURLOPT_TIMEOUT, $second);
            //这里设置代理，如果有的话
            //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
            //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
            curl_setopt($ch,CURLOPT_URL, $url);
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
            //设置header
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            //要求结果为字符串且输出到屏幕上
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            //post提交方式
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
            //运行curl
            $data = curl_exec($ch);
            curl_close($ch);
            //返回结果
            if($data)
            {
                curl_close($ch);

                $resul = $this->xmlToArray( $data );

                $newpara['package'] = "prepay_id=".$resul['prepay_id'];
                $newpara['appId'] = $resul['appid'];
                $timeStamp = time();
                $newpara['timeStamp'] = "$timeStamp";
                $newpara['nonceStr'] = createNoncestr();
                $newpara["signType"] = "MD5";
                /*重新计算签名sign*/

                ksort($newpara);
                $signstr = "";
                $i = 0;
                foreach( $newpara as $key=>$item )
                {
                    if( $item == "" || $item == null )
                    {
                        continue;
                    }
                    if( $i == 0 )
                    {
                        $signstr = $key."=".$item;
                    }else{
                        $signstr = $signstr."&".$key."=".$item;
                    }
                    $i++;
                }

                $signstr = $signstr."&key=".$secret;
                $signstr = md5($signstr);
                $newpara['paySign'] = strtoupper($signstr);


                // 测试
                $pringary = $newpara;

                $xml = $this->arrayToXml($pringary);
//                file_put_contents("asign.txt","paySign====".$newpara['paySign'],FILE_APPEND);
//                file_put_contents("asign.txt","\r\n",FILE_APPEND);
//                file_put_contents("asign.txt",$xml,FILE_APPEND);
//                file_put_contents("asign.txt","\r\n",FILE_APPEND);


                $this->assign("jsApiParameters",json_encode($newpara));


                $this->display( "wechatpay" );
                exit();
//                return $data;
            }
            else
            {
                $error = curl_errno($ch);
                echo "curl出错，错误码:$error"."<br>";
                echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
                curl_close($ch);
                return false;
            }
        }



        /**
         * 格式化参数格式化成url参数
         */
        public function ToUrlParams($ary)
        	{
        		$buff = "";
        		foreach ($ary as $k => $v)
        		{
        			if($k != "sign" && $v != "" && !is_array($v)){
        				$buff .= $k . "=" . $v . "&";
        			}
        		}

        		$buff = trim($buff, "&");
        		return $buff;
        	}


        /**
         * 	作用：将xml转为array
         */
        public function xmlToArray($xml)
        {
            //将XML转为array
            $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
            return $array_data;
        }


        /*获得用户的openid*/
        public function GetPayOpenid(){

            //通过code获得openid

            if (!isset($_GET['code'])){
                //触发微信返回code码
                $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING']);
                $url = $this->createOauthUrlForCode($baseUrl);
                // echo $url;
                // exit();
                Header("Location: $url");
                exit();
            } else {
                //获取code码，以获取openid
                $code = $_GET['code'];
                $openid = $this->getOpenidFromMp($code);
                return $openid;
            }
        }


         /**
         * 	作用：生成可以获得code的url
         */
        function createOauthUrlForCode($redirectUrl)
        {
            $urlObj["appid"] = "wxe7d2cf27b4cd9b87";
            $urlObj["redirect_uri"] = "$redirectUrl";
            $urlObj["response_type"] = "code";
            $urlObj["scope"] = "snsapi_base";
            $urlObj["state"] = "STATE"."#wechat_redirect";
            $bizString = $this->formatBizQueryParaMap($urlObj, false);
            return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
        }

        /**
         * 	作用：生成可以获得openid的url
         */
        function createOauthUrlForOpenid($code)
        {
            $urlObj["appid"] = "wxe7d2cf27b4cd9b87";
            $urlObj["secret"] = "3d665477895ec522c4b8d33ff04b8460";
            $urlObj["code"] = $code;
            $urlObj["grant_type"] = "authorization_code";
            $bizString = $this->formatBizQueryParaMap($urlObj, false);
            return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
        }


        /**
         * 	作用：格式化参数，签名过程需要使用
         */
        function formatBizQueryParaMap($paraMap, $urlencode)
        {
            $buff = "";
            ksort($paraMap);
            foreach ($paraMap as $k => $v)
            {
                if($urlencode)
                {
                   $v = urlencode($v);
                }
                //$buff .= strtolower($k) . "=" . $v . "&";
                $buff .= $k . "=" . $v . "&";
            }
            $reqPar;
            if (strlen($buff) > 0)
            {
                $reqPar = substr($buff, 0, strlen($buff)-1);
            }
            return $reqPar;
        }

        public function GetOpenidFromMp($code)
        {
            $url = $this->createOauthUrlForOpenid($code);
            //初始化curl
            $ch = curl_init();
            //设置超时
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//            if(WxPayConfig::CURL_PROXY_HOST != "0.0.0.0"
//                && WxPayConfig::CURL_PROXY_PORT != 0){
//                curl_setopt($ch,CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST);
//                curl_setopt($ch,CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT);
//            }
            //运行curl，结果以jason形式返回
            $res = curl_exec($ch);
            curl_close($ch);
            //取出openid
            $data = json_decode($res,true);
            $this->data = $data;
            $openid = $data['openid'];

            return $openid;
        }

        /*xin支付*/
        public function indexxin(){
    //        amount : 金额（单位为分），非空
    //        backurl : 支付结束跳转地址，非空
    //        desc : 商品描述，200位以内，可以为空
    //        extra : 透传参数，32位以内，可以为空
    //        merch : 商户id，平台分配
    //        notifyurl : 同步地址，非空
    //        product : 商品名称，64位以内，非空
    //        type : 支付场景 , （微信公众号为1,微信扫码为2,  微信H5为12,  支付宝H5为7）
    //        sign : 签名，非空，见附表一

//            $tjurl = "http://api.xiipay.com/Pay";
            $tjurl = "http://123.207.4.150:5880/Pay";
            $secret = "2897d756dcc7c7abfd6822ef1774762e";
            $para = array();
            $para['amount'] = $_GET['price'] * 100;
            $para['backurl'] = $this->getWxConfigHost();
            $para['desc'] = "微云投";
            $para['extra'] = $_GET['out_trade_no'];// 透传参数，就是我们的订单号
            $para['merch'] = "1724283130";
            $para['notifyurl'] = $this->getWxConfigHost().'/wap/wxpay/notifyurlxin';
            $para['product'] = "gold";
            $para['type'] = "1";
            $para['sign'] = "";
            $signstr = "amount=".$para['amount']."&backurl=".$para['backurl']."&desc=".$para['desc']."&extra=".$para['extra']."&merch=".$para['merch']."&notifyurl=".$para['notifyurl']."&product=".$para['product']."&type=".$para['type']."&key=".$secret;
            $para['sign'] = md5( $signstr );

            $updatePlat['plat'] = "xin";
            M('juejin_payorder')->where(['ordersn'=>$_GET['out_trade_no']])->save($updatePlat);
/*
------------------------------------------------------------
    edit by psycho@20170928
------------------------------------------------------------
*/
//        if($_GET['out_trade_no']){
//            $updateOrderPrize['price'] = $_GET['price'];
//            $order = M('juejin_payorder')->where(['ordersn'=>$_GET['out_trade_no']])->save($updateOrderPrize);
//        }
/*
------------------------------------------------------------
*/


            $second = 30;
            $parastr = "";
            $i = 0;
            foreach ($para as $key => $val) {
                if( $i == 0 )
                {
                     $parastr = '?' . $key . '=' . $val;
                }else{
                     $parastr = $parastr.'&' . $key . '=' . $val;
                }
                $i++;
            }

            $tjurl = $tjurl.$parastr;
            $ch = curl_init(  );
            //设置超时
            curl_setopt($ch, CURLOPT_TIMEOUT, $second);
            //这里设置代理，如果有的话
            //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
            //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
            curl_setopt($ch,CURLOPT_URL, $tjurl);
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
            curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
            //设置header
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            //要求结果为字符串且输出到屏幕上
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            //post提交方式
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
            //运行curl
            $data = curl_exec($ch);
            curl_close($ch);
            $str = var_export( $data, true );
            file_put_contents( "xin.txt", $str, FILE_APPEND );
            file_put_contents( "xin.txt", "\r\n", FILE_APPEND );
            if($data)
            {
                $a1 = json_decode( $data, true );
                $a2 = $a1['payurl'];

                @header("Location:$a2");
            }else{
                echo "支付失败";
            }
        }

        /*xin支付的结束跳转地址*/
        public function notifyurlxin(){
            /*
            $price = 0.97 * floatval( $price );
            $price = sprintf("%.2f", $price);
            */

            $secret = "2897d756dcc7c7abfd6822ef1774762e";
            $para = array();
            $para['amount'] = $_GET['amount'];
            $para['extra'] = $_GET['extra'];
            $para['order'] = $_GET['order'];
            $para['time'] = $_GET['time'];
            $para['sign'] = $_GET['sign'];
            $para['trade'] = $_GET['trade'];

            $signstr = "amount=".$para['amount']."&extra=".$para['extra']."&order=".$para['order']."&time=".$para['time']."&key=".$secret;
            $sign = md5( $signstr );
            if( $sign ==  $para['sign'] ){
                $this->addmoney( $para['extra'],$para['amount'], "xin" );
            }else{
            }
        }



}
?>
